package org.ncibi.cytoscape.metscape.utils;

import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import cytoscape.Cytoscape;
import cytoscape.CytoscapeInit;
import cytoscape.util.CyFileFilter;

public class FileUtils {
	public static int LOAD = 1;
	public static int SAVE = 2;
	
	public static File getFile(String title, int load_save) {
		return getFile(title, load_save, null, null);
	}
	
	public static File getFile(String title, int load_save, String extension, String description) {
		JFileChooser chooser = new JFileChooser(CytoscapeInit.getMRUD());
		int returnVal = JFileChooser.CANCEL_OPTION;
		File selectedFile = null;
		chooser.setDialogTitle(title);
		if(extension != null) {
			chooser.setAcceptAllFileFilterUsed(false);
			chooser.setFileFilter(new CyFileFilter(extension,description));
		}
		if(load_save == LOAD) {
			do {
				returnVal = chooser.showOpenDialog(Cytoscape.getDesktop());
				selectedFile = chooser.getSelectedFile();
			}
			while(returnVal == JFileChooser.APPROVE_OPTION && !selectedFile.exists());
		}
		else if(load_save == SAVE) {
			do {
				returnVal = chooser.showSaveDialog(Cytoscape.getDesktop());
				selectedFile = chooser.getSelectedFile();
				if(selectedFile == null)
					return null;
				
				if(extension != null && !selectedFile.getName().endsWith("."+extension))
					selectedFile = new File(selectedFile.getPath()+"."+extension);
				if(returnVal == JFileChooser.APPROVE_OPTION && selectedFile.exists()) {
					int answer = JOptionPane.showConfirmDialog(chooser, 
							"The file '"+selectedFile.getName()+"' already exists. Are you sure you want to overwrite it?",
							"File Exists", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
					if (answer == JOptionPane.YES_OPTION) 
						break;
				}
			}
			while(returnVal == JFileChooser.APPROVE_OPTION && selectedFile.exists());
		}
		if(returnVal == JFileChooser.APPROVE_OPTION){
			CytoscapeInit.setMRUD(chooser.getCurrentDirectory());
			return selectedFile;
		}
		else
			return null;
	}

}
